//
//  SESearchBarView.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/4/6.
//

import UIKit

typealias SESearchBarViewClosure = () -> Void

@IBDesignable class SESearchBarView: UIView {
    
    var searchClosure: SESearchBarViewClosure?

    var view: UIView!
    
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var placeholderLabel: UILabel!
    
    @IBInspectable var image: UIImage? {
        get { imageView.image }
        set { imageView.image = newValue }
    }
    
    @IBInspectable var placeholder: String? {
        get { placeholderLabel.text }
        set { placeholderLabel.text = newValue }
    }
    
    @IBInspectable var placeholderColor: UIColor {
        get { placeholderLabel.textColor }
        set { placeholderLabel.textColor = newValue }
    }
    
    @IBInspectable var bgColor: UIColor? {
        get { view.backgroundColor }
        set { view.backgroundColor = newValue }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    private func setupUI() {
        view = loadViewFromNib()
        view.backgroundColor = .white
        view.setLayerCorners(rect: view.bounds, radius: view.bounds.size.height / 2)
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(_tapToSearch))
        view.addGestureRecognizer(tapGesture)
    }
    
    @objc private func _tapToSearch() {
        searchClosure?()
    }
    
    func loadViewFromNib() -> UIView {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: nibName(), bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView

        view.frame = bounds
        view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        addSubview(view)

        return view
    }

    private func nibName() -> String {
        return String(describing: type(of: self))
    }

}
